package com.example.mq.rocketmq.service;

import com.example.mq.rocketmq.dataobject.Order;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 测试事务消息
 *
 * @author luowj12
 * @since 2021/6/9 15:22
 */
@Service
public class OrderServiece {

    private static final String TX_PRODUCER_GROUP = "demo-producer-group1";

    private static final String TX_PRODUCER_TOPIC = "DEMO_01";

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void delete(String orderNo) {
        Order order = new Order(3,1,1);
            String transactionId = UUID.randomUUID().toString();

        Message message =  MessageBuilder.withPayload( order).setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId)
                .setHeader("order_id",order.getId())
                .build();
            //如果可以删除订单则发送消息给rocketmq，让用户中心消费消息
            rocketMQTemplate.sendMessageInTransaction(TX_PRODUCER_GROUP,TX_PRODUCER_TOPIC,
                    message,orderNo
            );

    }

}
